// 防止sql注入和xss攻击
export default defineEventHandler(async (event) => {
    // 是否校验通过
    let isPass = true;
    // 获取请求参数
    const body = await readBody(event);
    const query = getQuery(event);

    // SQL注入检测函数
    const hasSqlInjection = (str: string): boolean => {
        const sqlPattern = /(select|update|delete|insert|drop|union|exec|;|')/i
        return sqlPattern.test(str)
    }

    // XSS攻击检测函数 
    const hasXssAttack = (str: string): boolean => {
        const xssPattern = /<[^>]*script|javascript:|onerror=|onclick=|onload=/i
        return xssPattern.test(str)
    }

    // 检查请求体
    if (body) {
        const bodyStr = JSON.stringify(body)
        if (hasSqlInjection(bodyStr)) {
            console.log('检测到SQL注入攻击');
            isPass = false;
        }
        if (hasXssAttack(bodyStr)) {
            console.log('检测到XSS攻击');
            isPass = false;
        }
    }

    // 检查URL参数
    if (query) {
        const queryStr = JSON.stringify(query)
        if (hasSqlInjection(queryStr)) {
            console.log('检测到SQL注入攻击');
            isPass = false;
        }
        if (hasXssAttack(queryStr)) {
            console.log('检测到XSS攻击');
            isPass = false;
        }
    }
    if (!isPass) {
        console.log('非法请求');
        return illegalInputResponse();
    }
})

